<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="queryParams.supplierId" placeholder="请选择供应商">
          <el-option
            v-for="dict in supplierList"
            :key="dict.supplierId"
            :label="dict.supplierName"
            :value="dict.supplierId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单时间">
        <el-date-picker
          v-model="daterangePurchaseDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="编号" prop="purchaseSn">
        <el-input
          v-model="queryParams.purchaseSn"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="purchaseState">
        <el-select v-model="queryParams.purchaseState" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.purchase_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单金额" prop="purchaseState">
        <NumberBetween ref="dto" v-model="daterangePurchaseTotal"></NumberBetween>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['webshop:GoodsPurchase:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['webshop:GoodsPurchase:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['webshop:GoodsPurchase:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['webshop:GoodsPurchase:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="GoodsPurchaseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="订单主键" align="center" prop="purchaseId"/>
      <el-table-column label="供应商" align="center" prop="supplierName"/>
      <el-table-column label="订单时间" align="center" prop="purchaseDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编号" align="center" prop="purchaseSn"/>
      <el-table-column label="说明" align="center" prop="purchaseInfo"/>
      <el-table-column label="合计总金额" align="center" prop="purchaseTotal"/>
      <el-table-column label="订单状态" align="center" prop="purchaseState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.purchase_state" :value="scope.row.purchaseState"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['webshop:GoodsPurchase:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['webshop:GoodsPurchase:remove']"

          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="form.supplierName" placeholder="请选择供应商" value-key="supplierId" @change="changeSelect">
            <el-option
              v-for="dict in supplierList"
              :key="dict.supplierId"
              :label="dict.supplierName+'('+dict.supplierId+')'"
              :value="dict"
            />
          </el-select>


          <el-button @click="selectSku" :disabled="disabled">选择商品</el-button>

        </el-form-item>
        <el-form-item label="订单时间" prop="purchaseDate">
          <el-date-picker clearable
                          v-model="form.purchaseDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择订单时间">
          </el-date-picker>
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="编号" prop="purchaseSn">
              <el-input v-model="form.purchaseSn" placeholder="请输入编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="说明" prop="purchaseInfo">
              <el-input v-model="form.purchaseInfo" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合计总金额" prop="purchaseTotal">
              <el-input v-model="form.purchaseTotal" placeholder="请输入合计总金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="订单状态" prop="purchaseState" v-if=" form.purchaseId != null">
          <el-radio-group v-model="form.purchaseState">
            <el-radio
              v-for="dict in dict.type.purchase_state"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

      <el-table v-loading="loading" :data="purchaseDetailList" v-if="purchaseDetailList.length>0">
        <el-table-column label="商品"  align="center" prop="goodsName" />
        <el-table-column label="商品标题"  align="center" prop="skuTitle" width="200px" :formatter="formatStr" />
        <el-table-column label="原价(市场标价格)"  align="center" prop="skuPrice" />
        <el-table-column label="当前价格"  align="center" prop="skuNowPrice" />
        <el-table-column label="数量"  align="center"  >
          <template slot-scope="scope">
            <el-input-number value="1" v-model="scope.row.purchaseDetailCount" :min="1"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteSelectSku(scope.row)"
              v-hasPermi="['webshop:GoodsPurchase:remove']"
            >删除</el-button>
          </template>
        </el-table-column>



      </el-table>
    </el-dialog>


    <SelectSku ref="ss" v-if="showSelectSku" @onSelectSku="selectHandle"></SelectSku>


  </div>
</template>

<script>
import {
  cheakPurchaseSn,
  listGoodsPurchase,
  getGoodsPurchase,
  delGoodsPurchase,
  addGoodsPurchase,
  updateGoodsPurchase
} from "@/api/webshop/GoodsPurchase";
import {listSupplier} from "@/api/webshop/SupplierInfo"
import NumberBetween from "@/components/SmallComp/NumberBetween.vue"
import SelectSku from "./SelectSku.vue"

export default {
  name: "GoodsPurchase",
  dicts: ['purchase_state'],
  components: {
    NumberBetween, SelectSku
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购订单表格数据
      GoodsPurchaseList: [],
      supplierList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      disabled: true,
      showSelectSku:false,

      // 订单状态时间范围
      daterangePurchaseDate: [],
      daterangePurchaseTotal: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplierId: null,
        purchaseSn: null,
        purchaseState: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        purchaseSn: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('订单编号不能为空'));
              }
              cheakPurchaseSn(value.trim()).then(response => {
                if (!response.data) {
                  callback(new Error('订单编号已经被使用,请重新输入'));
                } else {
                  callback();
                }
              })
            }, trigger: 'blur'
          }
        ]
      },
      purchaseDetailList:[

      ]
    };
  },
  created() {
    this.getList();
    this.getSupplierList();
  },
  watch: {
    "form.supplierId": {
      handler(val) {
        console.log(val)
        if (val) {
          this.disabled = false
        } else {
          this.disabled = true

        }
      }
    },
    "purchaseDetailList":{
      deep:true,
      handler(list){
        let total = 0.0;
        list.forEach(item=> {
          total += parseInt(item.purchaseDetailCount) * parseFloat(item.purchaseDetailPrice);
        })
        this.form.purchaseTotal = total
      }
    }
  }
  ,
  methods: {

    handleDeleteSelectSku(row){
      console.log(row)

      let number = this.purchaseDetailList.indexOf(row);
      this.purchaseDetailList.splice(number,1)
    },
    selectHandle(ids){
      console.log("asdads",ids)
      // this.purchaseDetailList=ids
      ids.forEach(sku=>{
        this.purchaseDetailList.push({
          skuId:sku.skuId,
          purchaseDetailCount:1,
          purchaseDetailPrice:sku.skuPrice,
          goodsName:sku.goodsName,
          skuTitle:sku.skuTitle,
          skuPrice:sku.skuPrice,
          skuNowPrice:sku.skuNowPrice,
        })
      })
      // this.showSelectSku = false;

    },
    changeSelect(sel){
      console.log(sel)

      this.form.supplierId = sel.supplierId
      console.log("form",this.form)

      this.form.supplierName = sel.supplierName
      this.purchaseDetailList = []
    },
    /** 说明的字符串截取  */
    formatStr(row, column, cellValve, index) {
      // console.log(row, column,cellValve,index)
      return cellValve.length > 10 ? cellValve.substr(0, 10) + "..." : cellValve
    },
    selectSku() {
      this.showSelectSku = true;
      this.$nextTick(() => {
        console.log("this.purchaseDetailList",this.purchaseDetailList)
        let ids = this.purchaseDetailList.map(item => item.skuId)
        console.log("idssss",ids)
        // 这里可以安全地访问和操作基于新数据渲染的 DOM
        this.$refs.ss.init(this.form.supplierId,this.form.supplierName,ids)
      });

      // if (this.form.supplierId) {
      //   this.disabled=false;
      // }
    }
    ,
    getSupplierList() {
      listSupplier().then(response => {
        this.supplierList = response;
      });
    },
    /** 查询采购订单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangePurchaseDate && '' != this.daterangePurchaseDate) {
        this.queryParams.params["beginPurchaseDate"] = this.daterangePurchaseDate[0];
        this.queryParams.params["endPurchaseDate"] = this.daterangePurchaseDate[1];
      }
      if (null != this.daterangePurchaseTotal && '' != this.daterangePurchaseTotal) {
        console.log(this.daterangePurchaseTotal)
        this.queryParams.params["beginPurchaseTotal"] = this.daterangePurchaseTotal[0];
        this.queryParams.params["endPurchaseTotal"] = this.daterangePurchaseTotal[1];
      }
      listGoodsPurchase(this.queryParams).then(response => {
        this.GoodsPurchaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        purchaseId: null,
        supplierId: null,
        purchaseDate: null,
        purchaseSn: null,
        purchaseInfo: null,
        purchaseTotal: 0.0,
        purchaseState: 0,
        purchaseDetailCount:1,
        children:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangePurchaseDate = [];
      this.daterangePurchaseTotal = [];
      this.$refs['dto'].reset();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.purchaseId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购订单";
      this.purchaseDetailList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const purchaseId = row.purchaseId || this.ids
      getGoodsPurchase(purchaseId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购订单";
      });
    },
    /** 提交按钮 */
    submitForm() {




      this.form.children = this.purchaseDetailList
//       console.log(this.form.children)
// return
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.purchaseId != null) {
            updateGoodsPurchase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoodsPurchase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purchaseIds = row.purchaseId || this.ids;
      this.$modal.confirm('是否确认删除采购订单编号为"' + purchaseIds + '"的数据项？').then(function () {
        return delGoodsPurchase(purchaseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('webshop/GoodsPurchase/export', {
        ...this.queryParams
      }, `GoodsPurchase_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
